package com.example.forum.controller;


import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.Message;
import com.example.forum.model.User;
import com.example.forum.services.IMessageService;
import com.example.forum.services.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;


@Api(tags = "站内信接口")
@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {



    @Resource
    private IUserService userService;

    @Resource
    private IMessageService messageService;
    @ApiOperation("发送站内信")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @ApiParam("接受者id") @RequestParam("receiveUserId") @NonNull Long receiveUserId,
                          @ApiParam("内容") @RequestParam("content") @NonNull String content) {

        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        //1 当前登录用户状态 禁言状态不能发送站内信
        if(user.getState() == 1) {
            // 返回用户状态异常
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //2 不能给自己发送站内信
        if(user.getId().equals(receiveUserId)) {
            return AppResult.failed("不能给自己发送站内信");
        }
        //3 校验接受者是否存在
        User receiveUser = userService.SelectById(receiveUserId);
        if(receiveUser == null || receiveUser.getDeleteState() == 1) {
            //返回接受者状态异常
            return AppResult.failed("接受者状态异常");
        }
        //4 封装对象
        Message message = new Message();
        message.setPostUserId(user.getId());  //发送者id
        message.setReceiveUserId(receiveUserId); //接受者id
        message.setContent(content);  //站内信内容
        //5 调用service
        messageService.create(message);
        //6 返回结果
        return AppResult.success("发送成功");
    }



    @ApiOperation("获取未读数量")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount (HttpServletRequest request) {
        //1 获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        //2 调用service方法
        Integer count = messageService.selectUnreadCount(user.getId());  //当前登录用户ID就是接受者
        //3 返回结果
        return AppResult.success(count);
    }

    @ApiOperation("查询用户的所有站内信")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request) {
        //获取当前登录的用户 并得到用户id
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        //调用service
        List<Message> messages = messageService.selectByReceiveUserId(user.getId());
        //返回结果
        return AppResult.success(messages);
    }



    @ApiOperation("更新为已读")
    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,
                              @ApiParam("站内信id") @RequestParam("id") @NonNull Long id) {
        //1 根据id查询站内信
        Message message = messageService.selectById(id);
        //2 校验站内信是否存在
        if(message == null || message.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        //3 站内信是不是自己的
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        if(!user.getId().equals(message.getReceiveUserId())) {
            //返回错误信息  站内信不是自己的
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //4 调用service  把这个站内信的状态更新为已读
        messageService.updateStateById(id, (byte) 1);
        // 返回结果
        return AppResult.success();
    }


    /**
     * 回复站内信
     * @param request
     * @param repliedId  要回复的站内信id
     * @param content 站内信内容
     * @return
     */
    @ApiOperation("回复站内信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @ApiParam("要回复的站内信id") @RequestParam("repliedId")  @NonNull Long repliedId,
                           @ApiParam("站内信内容") @RequestParam("content")  @NonNull String content) {

        //校验当前登录用户状态
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1) {
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //校验要回复的站内信状态
        Message existsMessage = messageService.selectById(repliedId);
        if(existsMessage == null || existsMessage.getDeleteState() == 1) {
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        //不能给自己回复
        if(user.getId().equals(existsMessage.getPostUserId())) {
            //返回错误描述
            return AppResult.failed("不能给自己的站内信回复: 失败");
        }
        //构造发送者和接收者,正文
        Message message = new Message();
        message.setPostUserId(user.getId());   //发送者就是当前登录用户
        message.setReceiveUserId(existsMessage.getPostUserId());   //接受者就是要回复的站内信里面的发送者
        message.setContent(content);
        //调用service
        messageService.reply(repliedId,message);
        //返回结果
        return AppResult.success();
    }
}
